/* -----------------
* brief
* 1. this is code gen by tools
 */

package service

import (
	"github.com/mjiulee/lego"
	. "saas_sys_base/modules/eshop/models"
)

type EShopService struct {
	// add your model here
	tbEShop EShop
	logService ShopAccountLogService
}

func (t *EShopService) ListEShop(keyword string, page, psize int) ([]map[string]string, int64, error) {
	// 业务查询
	queryMap := map[string]interface{}{
		"table":  map[string]string{"table": "tb_e_shop", "alias": "t1"},
		"fields": []string{"t1.*", "t2.cate_name,t3.name as tenant_name"},
		"join": []map[string]string{
			map[string]string{"table": "tb_shop_cate as t2", "on": "t2.id = t1.cate_id"},
			map[string]string{"table": "tb_tenant as t3", "on": "t3.id = t1.tenant_id"},
		},
		"where": []lego.QMapWhereField{
			{"t1.if_del", "=", 0, "AND", false},
		},
		"search": map[string]string{
			"t1.shop_name": keyword,
		},
		"orders": []string{"t1.id asc"},
		"page": map[string]int{
			"page":  page,
			"psize": psize,
		},
	}
	return lego.QueryListByMap(queryMap)
}

/* 根据id获取记录
 * -----------------
 */
func (t *EShopService) GetEShopById(id int64) *EShop {
	return t.tbEShop.RecodeById(id)
}

func (t *EShopService) GetEShopByTenantId(tenantId int64) *EShop {
	return t.tbEShop.RecodeByTenantId(tenantId)
}

/* 添加
 * -----------------
 */
func (t *EShopService) SaveEShop(item2add *EShop) bool {
	return t.tbEShop.AddRecode(item2add)
}

/* 删除(硬删除)*/
func (t *EShopService) DelEShopById(id int64) bool {
	return t.tbEShop.DelRecodeById(id)
}

/* 更新
 * -----------------*/
func (t *EShopService) UpdateEShop(rc *EShop) bool {
	return t.tbEShop.UpdateRecode(rc)
}

func (t *EShopService) ListByTenandId(tenantId int64) []*EShop {

	shopTenantList := t.tbEShop.ListByTenandId(tenantId)
	var shopList []*EShop = make([]*EShop, len(shopTenantList))

	for i,v := range shopTenantList {
		shopList[i] = v.EShop
		shopList[i].RegisterState = v.Tenant.RegisterState
		shopList[i].IsPayed = v.Tenant.IsPayed
	}
	return shopList
}


func (t *EShopService) AddEShopBalance(rc *EShop,balabce int64,businessType,incomeType,isFreeze int,sourceId int64,sourceCode,description string ) bool {
	rc.Balance = rc.Balance + balabce
	var log = new(ShopAccountLog)
	log.Balance = balabce
	log.EShopId = rc.Id
	log.AfterBalance = rc.Balance
	log.BusinessType = businessType
	log.Description = description
	log.IncomeType = incomeType
	log.IsFreeze = isFreeze
	log.SourceCode = sourceCode
	log.SourceId = sourceId
	t.logService.SaveShopAccountLog(log)
	return true
}